package Controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import Entities.LoginEntity;
import GUI.MakeOfferGUI;
import Server.RsWraper;
import Server.Tuple;

/**
 * The Class MakeOfferController.
 * Controller for making an offer for customer activity.
 */
public class MakeOfferController implements Observer{

	/** The make offer gui. */
	private MakeOfferGUI makeOfferGui;
	
	/** The login entity. */
	private LoginEntity loginEntity;
	
	/** The previous controller. */
	private SalesManController prev;
	
	/** The offers. */
	private ArrayList<Tuple> offers=new ArrayList<Tuple>();
	
	/** The choose. */
	private String []choose;
	
	/** The delete. */
	private String delete;
	
	/** The operation. */
	int operation=0;
	
	/** The no response. */
	int noResponse=0;
	
	/**
	 * Instantiates a new make offer controller.
	 *
	 * @param makeOfferGui the make offer gui
	 * @param loginEntity the login entity
	 */
	public MakeOfferController(MakeOfferGUI makeOfferGui,
			LoginEntity loginEntity) {
		
		this.makeOfferGui=makeOfferGui;
		this.loginEntity=loginEntity;
		ClientController.setObserver(this);
		this.makeOfferGui.addMakeOfferActionListener(new MakeOffer());
		this.makeOfferGui.addBackActionListener(new BackListener());
		this.makeOfferGui.setVisible(true);
		addCustomersOffersToCb();	
	}

	/**
	 * Adds the customers offers to cb.
	 */
	private void addCustomersOffersToCb()
	{
		String query = "SELECT servesinsale.sid,servesinsale.cid,sales.date,sales.period,sales.location,mp.pname,mp.pid FROM"
				+ " servesinsale,sales,mp WHERE servesinsale.eid = '"+loginEntity.getUid()+"' AND"
				+ " servesinsale.sid = sales.sid AND"
				+ "  sales.mpid = mp.mpid";
		try {
			ClientController.observableClient.sendToServer(query);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	
	/* (non-Javadoc)
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 */
	@Override
	public void update(Observable arg0, Object arg1) {
		if(operation==0)
		{
			if(!arg1.toString().equals("empty query")&&!arg1.toString().equals("error"))
			{
				offers=new ArrayList<Tuple>();
					offers.addAll(((RsWraper)arg1).getRows());
					if(operation==0)
			for(int i=0;i<offers.size();i++)
			{
				//customersList[i]=customers.get(i).get("UID")+","+customers.get(i).get("NAME");
				makeOfferGui.getOfferCB().addItem(offers.get(i).get("SID")+","+offers.get(i).get("CID")+","+offers.get(i).get("DATE")+","+offers.get(i).get("PERIOD")+","+offers.get(i).get("LOCATION")+","+offers.get(i).get("PNAME")+","+offers.get(i).get("PID"));
			}
			}
			else
			makeOfferGui.displayWarningMessage("There are not any offers");
		}
		else if(operation==1)
		{
			if(!arg1.toString().equals("empty query")&&!arg1.toString().equals("error"))
			{
				offers=new ArrayList<Tuple>();
			//	offers.addAll(((RsWraper)arg1).getRows());
			//	offers=((RsWraper)arg1).getRows();
				String str=((RsWraper)arg1).getRows().get(0).get("LASTREQUEST");
					if(!str.equals(" "))
					{
						String[] date=str.split("/");
						int eyear=Integer.parseInt(date[0]);
						int emonth=Integer.parseInt(date[1]);
						int eday=Integer.parseInt(date[2]);
						long year=eyear*12*31*24*3600*1000;
						long month=emonth*31*24*3600*1000;
						long day=eday*24*3600*1000;
						int cyear=(new Date().getYear());
						int cmonth=(new Date().getMonth());
						int cday=new Date().getDate();
						long year1=(cyear+1900)*12*31*24*3600*1000;
						long month1=(cmonth+1)*31*24*3600*1000;
						long day1=cday*24*3600*1000;
				if(year+month+day+7*24*3600*1000<=(year1+month1+day1)){
					int quantity;
					String query = null;
				//make offer(update entry)
					if((quantity=randomOffer())!=0)
					{
						String phonetime=00+":"+(randomValue()+10)+":"+(randomValue()+10);
					query="UPDATE customersresponsestooffer SET" +
						" `quantity`='"+quantity+"',`customerResponse`='YES', `phonetime`='"+phonetime+"' WHERE" +
						" customersresponsestooffer.sid= '"+Integer.parseInt(choose[0])+"' AND customersresponsestooffer.cid= '"+choose[1]+"'";
					makeOfferGui.getOfferCB().remove(makeOfferGui.getOfferCB().getSelectedIndex());
					}
					if(randomOffer()==0)
					{
						noResponse=1;
						quantity=quantity+randomValue();
						String phonetime=00+":"+(randomValue()+10)+":"+(randomValue()+10);
						query="UPDATE customersresponsestooffer SET" +
								" `quantity`='"+quantity+"',`customerResponse`='NO',`customerResponse`='do not want to buy', `phonetime`='"+phonetime+"' WHERE" +
								" customersresponsestooffer.sid= '"+Integer.parseInt(choose[0])+"' AND customersresponsestooffer.cid= '"+choose[1]+"'";		
					}
					try {
						ClientController.observableClient.sendToServer(query);
					} catch (IOException e) {
						e.printStackTrace();
				}
					operation=2;
				}
				else
				{
					makeOfferGui.displayWarningMessage("you need to wait one week before you make an offer");
				}
			}
					else
					{
						//make offer(new entry)
						String query;
						int quantity=randomOffer();
						String phonetime=00+":"+(randomValue()+10)+":"+(randomValue()+10);
						operation=2;
						if(quantity==0)
						{
							noResponse=1;
						quantity=quantity+randomValue();	
						query="INSERT INTO customersresponsestooffer (`sid`,`cid`,`pid`,`quantity`,`customerResponse`,`description`,`phonetime`) VALUES" +
						" ('"+Integer.parseInt(choose[0])+"','"+choose[1]+"','"+Integer.parseInt(choose[6])+"','"+quantity+"','NO','do not want to buy','"+phonetime+"')";
						}
						else
						{
							query="INSERT INTO customersresponsestooffer (`sid`,`cid`,`pid`,`quantity`,`customerResponse`,`phonetime`) VALUES" +
									" ('"+Integer.parseInt(choose[0])+"','"+choose[1]+"','"+Integer.parseInt(choose[6])+"','"+quantity+"','YES','"+phonetime+"')";
							makeOfferGui.getOfferCB().remove(makeOfferGui.getOfferCB().getSelectedIndex());
						}
						try {
							ClientController.observableClient.sendToServer(query);
						} catch (IOException e) {
							e.printStackTrace();
					}
						operation=2;
					}

			}
			else
				makeOfferGui.displayWarningMessage("Error");
			
		}
		else if(operation==2)
		{
			if(!arg1.toString().equals("empty query")&&!arg1.toString().equals("error"))
			{
			String query;
			String date=(new Date().getYear()+1900)+"/"+(new Date().getMonth()+1)+"/"+(new Date().getDate());
			query="UPDATE customers SET" +
					" `lastrequest`='"+date+"' WHERE" +
					" customers.cid= '"+choose[1]+"'";	
			try {
				operation=3;
				ClientController.observableClient.sendToServer(query);
			} catch (IOException e) {
				e.printStackTrace();
			}
			}
			else
				makeOfferGui.displayWarningMessage("Error");
		}
		else if(operation==3&&noResponse==0)
		{
			if(!arg1.toString().equals("empty query")&&!arg1.toString().equals("error"))
			{
			delete = "DELETE FROM servesinsale WHERE `sid`='"+Integer.parseInt(choose[0])+"' AND `cid`='"+choose[1]+"'";
			try {
				operation=4;
				ClientController.observableClient.sendToServer(delete);
			} catch (IOException e) {
				e.printStackTrace();
			}
			}
			else
				makeOfferGui.displayWarningMessage("Error");
		}
		else if(operation==4)
		{
			if(!arg1.toString().equals("empty query")&&!arg1.toString().equals("error"))
			{
			delete = "SELECT servesinsale.sid FROM servesinsale WHERE `sid`='"+Integer.parseInt(choose[0])+"'";
			try {
				operation=5;
				ClientController.observableClient.sendToServer(delete);
			} catch (IOException e) {
				e.printStackTrace();
			}
			}
			else
				makeOfferGui.displayWarningMessage("Error");
		}
		else if(operation==5)
		{
			if(arg1.toString().equals("empty query"))
			{
				delete = "DELETE FROM sales WHERE `sid`='"+Integer.parseInt(choose[0])+"'";
				try {
					operation=6;
					ClientController.observableClient.sendToServer(delete);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		
	}

	/**
	 * Random offer.
	 *
	 * @return the int
	 */
	private int randomOffer() {
		int num;
		Random random = new Random();
		num = random.nextInt(2);
		if(num==0)
			return 0;
		if(num==1)
			return random.nextInt(51);
		return 0;
		
	}
	
	/**
	 * Random value.
	 *
	 * @return the int
	 */
	private int randomValue() {
		Random random = new Random();
			return random.nextInt(50);
		
	}

	/**
	 * The Class MakeOffer.
	 */
	class MakeOffer implements ActionListener
	{

		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			
			choose=((String) makeOfferGui.getOfferCB().getSelectedItem()).split(",");
			int eyear=Integer.parseInt(choose[2].substring(6,10));
			int emonth=Integer.parseInt(choose[2].substring(3,5));
			int eday=Integer.parseInt(choose[2].substring(0,2));
			long year=eyear*12*31*24*3600*1000;
			long month=emonth*31*24*3600*1000;
			long day=eday*24*3600*1000;
			int cyear=(new Date().getYear());
			int cmonth=(new Date().getMonth());
			int cday=new Date().getDate();
			long year1=(cyear+1900)*12*31*24*3600*1000;
			long month1=(cmonth+1)*31*24*3600*1000;
			long day1=cday*24*3600*1000;
			if((year+month+day+Integer.parseInt(choose[3])*24*3600*1000)>(year1+month1+day1)){
						String query = "SELECT customers.lastrequest FROM"
								+ " customers WHERE"
								+ " customers.cid= '"+choose[1]+"'";
						operation=1;
						try {
							ClientController.observableClient.sendToServer(query);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
					else
						makeOfferGui.displayWarningMessage("The time of this sale was over");

		}
		
	}

	
	/**
	 * The listener interface for receiving back events.
	 * The class that is interested in processing a back
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addBackListener<code> method. When
	 * the back event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see BackEvent
	 */
	class BackListener implements ActionListener
	{

		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent arg0) {
			LoginController.mainWindow.setTitle("Sales man");
			LoginController.mainWindow.setContentPane(prev.getSmGUI());
		}
	
	}
	
	/**
	 * Sets the previous controller.
	 *
	 * @param prev the new previous controller
	 */
	public void setPrev(SalesManController prev) {
		this.prev = prev;
		
	}

}
